import React, { useState, useEffect, useCallback } from 'react'
import { Link } from 'react-router-dom'
import { Select, Table, Space, message } from 'antd'
import Nav from '../../components/nav'
import { fetchData } from '../../request'
import './index.scss'

  const dataTableDefault = [
    {
      key: '1',
      num: 32,
      time: '2020-7-9',
    },
    {
      key: '2',
      num: 32,
      time: '2020-7-9',
    },
    {
      key: '2',
      num: 32,
      time: '2020-7-9',
    },
    {
      key: '2',
      num: 32,
      time: '2020-7-9',
    }
  ];

  const manageList = {
    "ADMIN": "董事长",
    "GM": "副总",
    "CHAIRMAN": "总监",
    "MANAGE": "经理",
    "SP": "区域经理",
    "STAFF": "店长"
}

const manageData = [
    {key: "ADMIN", value: "董事长"},
    {key: "GM", value: "副总"},
    {key: "CHAIRMAN", value: "总监"},
    {key: "MANAGE", value: "经理"},
    {key: "SP", value: "区域经理"},
    {key: "STAFF", value: "店长"}
]

const PersonDetail = props => {

    const [ manage, setManage ] = useState(localStorage.getItem("role"))
    const [data, setData] = useState([{key: localStorage.getItem("id"), value: localStorage.getItem("userName")}])
    const [userId, setUserId] = useState(localStorage.getItem('id'))
    const [dataTable, setDataTable] = useState([]);
    const [dataTableWei, setDataTableWei] = useState([]);
    const [sum, setSum] = useState(0)
    const [sum1, setSum1] = useState(0)
    const [showT, setShowT] = useState(false)
    const [url, setUrl] = useState({
        method: "post",
        url: "/makeUp/account/member",
        data: {
            parentId: userId
        }
    })
    const [ orderUrl, setOrderUrl ] = useState({
        method: "post",
        url: "/makeUp/order/getOrder",
        data: {
          userId:  userId
        }
    })
    const [ weiOrderUrl, setWeiOrderUrl ] = useState({
      method: "post",
      url: "/makeUp/order/toExamine/list"
    })
    const [ sumUrl, setSumUrl ] = useState({
        method: "post",
        url: "/makeUp/order/count",
        data: {
          userId:  userId,
          type: 0
        }
    })
    const [ sumUrl1, setSumUrl1 ] = useState({
      method: "post",
      url: "/makeUp/order/count",
      data: {
        userId: userId,
        type: 1
      }
    })
    const [ sumUrlD, setSumUrlD ] = useState({
      method: "post",
      url: "/makeUp/order/count",
      data: {
        parentId:  localStorage.getItem('id'),
        type: 0
      }
    })
    const [ sumUrlD1, setSumUrlD1 ] = useState({
      method: "post",
      url: "/makeUp/order/count",
      data: {
        parentId: localStorage.getItem('id'),
        type: 1
      }
    })

    let nextPositionNUM =  _.findIndex(manageData, {key: localStorage.getItem('role')});
    let manageDataShow = manageData.slice(nextPositionNUM+1)
    // console.log(manageDataShow);

    useEffect(() => {
      fetchData(url).then(res => {
        setData([{key: localStorage.getItem('id'), value: localStorage.getItem('userName')}, ..._.map(res.data, item => ({key: item.id, value: item.userName}))])
      })
    }, [url])

    const getOrderTable = useCallback(() => {
      fetchData(orderUrl).then(res => {
        setDataTable(_.map(res.data.list, (item, i) => ({
          key: i,
          num: item.count,
          userId: item.userId,
          id: item.id,
          type: item.type == 0 ? "靓颜" : "透骨",
          status: item.status ? "通过" : "未审核"
        })))
      })
    }, [orderUrl, dataTable])

    useEffect(() => {
      getOrderTable()
    }, [orderUrl])

    const getCountAll = useCallback(() => {
      fetchData(sumUrl).then(res => {
        setSum(res.data.amount)
      })
      fetchData(sumUrl1).then(res => {
        setSum1(res.data.amount)
      })
    }, [sumUrl, sumUrl1])

    const getDongCount = useCallback(() => {
      fetchData(sumUrlD).then(res => {
        setSum(res.data.amount)
      })
      fetchData(sumUrlD1).then(res => {
        setSum1(res.data.amount)
      })
    })

    useEffect(() => {
      if(userId === localStorage.getItem('id') && localStorage.getItem("role") == "ADMIN" ){
        getDongCount()
      }else{
        getCountAll()
      }
    }, [sumUrl, sumUrl1, sumUrlD, sumUrlD1, userId])

    const handleChange = useCallback(val => {
        setUserId(val)
        setUrl({  
          method: "post",
          url: "/makeUp/account/member",
          data: {
              parentId: val
          }
        })
        setOrderUrl({
          method: "post",
          url: "/makeUp/order/getOrder",
          data: {
            userId:  val
          }
        })
        if(val === localStorage.getItem('id') && localStorage.getItem("role") == "ADMIN" ){
          setSumUrlD({
            method: "post",
            url: "/makeUp/order/count",
            data: {
              parentId: localStorage.getItem('id'),
              type: 0
            }
          })
          setSumUrlD1({
            method: "post",
            url: "/makeUp/order/count",
            data: {
              parentId: localStorage.getItem('id'),
              type: 1
            }
          })
        }else{
          setSumUrl({
            method: "post",
            url: "/makeUp/order/count",
            data: {
              userId: val,
              type: 0
            }
          })
          setSumUrl1({
            method: "post",
            url: "/makeUp/order/count",
            data: {
              userId: val,
              type: 1
            }
          })
        }
       
    },[url, orderUrl, sumUrl, sumUrl1, userId])

    const getWeiDataTable = useCallback(() => {
      fetchData(weiOrderUrl).then(res => {
        console.log("4445556666", res);
        setDataTableWei(_.map(res.data.list, (item, i) => ({
          key: i,
          num: item.count,
          type: item.type == 0 ? "靓颜" : "透骨",
          userId: item.userId,
          id: item.id,
          name: item.name,
          time: item.createdAt.slice(0, 10)
        })))
      })
    },[weiOrderUrl, dataTableWei])

    const showWeiShenOrder = useCallback(() => {
      getWeiDataTable()
      setShowT(true)
    }, [showT])
    const showMyOrder = useCallback(() => {
      getOrderTable()
      setShowT(false)
    },[showT])

    const hangleDelete = useCallback((record) => {
      console.log("dddddffffss", dataTable, record.key)
      fetchData({  
        method: "post",
        url: "/makeUp/order/remove",
        data: {
          id: dataTable[record.key].id
        }
      }).then(res => {
        if(res.code == 200){
          message.success('确认成功');
          getOrderTable();
          getCountAll();
        }
      })
    })

    const handleMakeSureOrder = useCallback((record) => {
      fetchData({  
        method: "post",
        url: "/makeUp/order/toExamine",
        data: {
          userId: dataTableWei[record.key].userId,
          id: dataTableWei[record.key].id
        }
      }).then(res => {
        console.log("dhdhdhdhdhhdhd", res);
        if(res.code == 200){
          message.success('确认成功');
          getWeiDataTable();
        }
      })
    })

    return (
        <div className="person-page">
            <div className="bg"></div>
            <div className="person-box">
                <Nav backUrl="/changePas"></Nav>
                <div className="select-box">
                    <Select
                        defaultValue={data && data.length > 0 && data[0].value}
                        onChange={handleChange}
                    >
                        {data && data.length > 0 && data.map(item => (
                            <Option key={item.key}>{item.value}</Option>
                        ))}
                    </Select>
                    <Link className="addPerson" to="/member">下属管理</Link>
                </div>
                <Link className="jiangli" to="/jiangli">奖励</Link>
                <div className="person-achievement">
                    <div className="person-total">
                        <div>{sum == null ? 0 : sum}瓶</div>
                    </div>
                    <div className="person-total">
                        <div>{sum1 == null ? 0 : sum1}瓶</div>
                    </div>
                    {localStorage.getItem("role") != "ADMIN" && <Link to="/orderType">新增订单</Link>}
                </div>
                <div className="order-button">
                  <div className="yi-order" style={{cursor: 'pointer', color: !showT ? "#ff0000":"#000000"}} onClick={showMyOrder}>我的订单</div>
                  {localStorage.getItem("role") != "STAFF" && <div className="wei-order" style={{cursor: 'pointer', color: showT ? "#ff0000":"#000000"}} onClick={showWeiShenOrder}>未审核订单</div>}
                </div>
                {!showT && <div className="person-order-list">
                  <Table columns={[
                      {
                        title: '数量',
                        dataIndex: 'num',
                        key: 'num',
                      },
                      {
                        title: '产品',
                        dataIndex: 'type',
                        key: 'type',
                      },
                      {
                        title: '状态',
                        dataIndex: 'status',
                        key: 'status',
                      },
                      {
                        title: '操作',
                        key: 'action',
                        render: (text, record) => (
                          <Space size="middle">
                            <a onClick={() => {hangleDelete(record)}}>删除</a>
                          </Space>
                        ),
                      },
                    ]}
                    dataSource={dataTable} 
                  />
                </div>}
                {showT && <div className="person-order-list">
                  <Table columns={[
                      {
                        title: '数量',
                        dataIndex: 'num',
                        key: 'num',
                      },
                      {
                        title: '产品',
                        dataIndex: 'type',
                        key: 'type',
                      },
                      {
                        title: '员工',
                        dataIndex: 'name',
                        key: 'name',
                      },
                      {
                        title: '操作',
                        key: 'action',
                        render: (text, record) => (
                          <Space size="middle">
                            <a onClick={() => {handleMakeSureOrder(record)}}>确认</a>
                          </Space>
                        ),
                      },
                    ]} 
                    dataSource={dataTableWei} 
                  />
                </div>}
            </div>
        </div>
    )
}

export default PersonDetail;